<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="goBack" fill="clear">
            <ion-icon :icon="arrowBackOutline"></ion-icon>
            返回
          </ion-button>
        </ion-buttons>
        <ion-title>注册</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="register-container">
        <!-- Logo 区域 -->
        <div class="logo-section">
          <ion-icon :icon="personAddOutline" size="large" color="primary"></ion-icon>
          <h1>创建账户</h1>
          <p>加入租房管理系统</p>
        </div>

        <!-- 注册表单 -->
        <form @submit.prevent="handleRegister" class="register-form">
          <ion-item>
            <ion-label position="stacked">姓名 *</ion-label>
            <ion-input
              v-model="registerForm.name"
              type="text"
              placeholder="请输入您的真实姓名"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">用户名 *</ion-label>
            <ion-input
              v-model="registerForm.username"
              type="text"
              placeholder="请输入用户名（至少3个字符）"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">密码 *</ion-label>
            <ion-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（至少6个字符）"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">确认密码 *</ion-label>
            <ion-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <!-- 表单验证提示 -->
          <div class="validation-hints" v-if="showValidationHints">
            <div class="hint-item" :class="{ valid: isNameValid }">
              <ion-icon :icon="isNameValid ? checkmarkCircleOutline : alertCircleOutline"></ion-icon>
              <span>姓名不能为空</span>
            </div>
            <div class="hint-item" :class="{ valid: isUsernameValid }">
              <ion-icon :icon="isUsernameValid ? checkmarkCircleOutline : alertCircleOutline"></ion-icon>
              <span>用户名至少3个字符</span>
            </div>
            <div class="hint-item" :class="{ valid: isPasswordValid }">
              <ion-icon :icon="isPasswordValid ? checkmarkCircleOutline : alertCircleOutline"></ion-icon>
              <span>密码至少6个字符</span>
            </div>
            <div class="hint-item" :class="{ valid: isPasswordMatch }">
              <ion-icon :icon="isPasswordMatch ? checkmarkCircleOutline : alertCircleOutline"></ion-icon>
              <span>两次密码输入一致</span>
            </div>
          </div>

          <ion-button
            expand="block"
            type="submit"
            :disabled="loading || !isFormValid"
            class="register-button"
          >
            <ion-spinner v-if="loading" name="crescent"></ion-spinner>
            <span v-else>注册</span>
          </ion-button>
        </form>

        <!-- 登录链接 -->
        <div class="login-link">
          <p>已有账户？ <ion-button fill="clear" @click="goToLogin">立即登录</ion-button></p>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonItem,
  IonLabel,
  IonInput,
  IonIcon,
  IonSpinner,
  alertController,
  toastController
} from '@ionic/vue'
import {
  arrowBackOutline,
  personAddOutline,
  checkmarkCircleOutline,
  alertCircleOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { register } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const registerForm = ref({
  name: '',
  username: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const showValidationHints = ref(false)

// 表单验证
const isNameValid = computed(() => registerForm.value.name.trim().length > 0)
const isUsernameValid = computed(() => registerForm.value.username.trim().length >= 3)
const isPasswordValid = computed(() => registerForm.value.password.length >= 6)
const isPasswordMatch = computed(() => 
  registerForm.value.password === registerForm.value.confirmPassword && 
  registerForm.value.confirmPassword.length > 0
)

const isFormValid = computed(() => 
  isNameValid.value && 
  isUsernameValid.value && 
  isPasswordValid.value && 
  isPasswordMatch.value
)

// 监听表单变化，显示验证提示
watch(registerForm, () => {
  showValidationHints.value = Object.values(registerForm.value).some(value => value.length > 0)
}, { deep: true })

// 处理注册
const handleRegister = async () => {
  if (!isFormValid.value) return

  loading.value = true

  try {
    const response = await register({
      name: registerForm.value.name.trim(),
      username: registerForm.value.username.trim(),
      password: registerForm.value.password
    })

    if (response.success && response.data) {
      // 保存用户信息到 store
      userStore.login(response.data.user, response.data.token)

      // 显示成功提示
      const toast = await toastController.create({
        message: '注册成功！请选择您的角色',
        duration: 3000,
        color: 'success',
        position: 'top'
      })
      await toast.present()

      // 跳转到角色选择页面
      router.replace('/role-select')
    } else {
      throw new Error(response.message || '注册失败')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    
    const alert = await alertController.create({
      header: '注册失败',
      message: error.message || '注册过程中发生错误，请重试',
      buttons: ['确定']
    })
    await alert.present()
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px 0;
}

.logo-section h1 {
  margin: 16px 0 8px 0;
  color: var(--ion-color-primary);
  font-weight: bold;
}

.logo-section p {
  color: var(--ion-color-medium);
  margin: 0;
}

.register-form {
  margin-bottom: 30px;
}

.register-form ion-item {
  margin-bottom: 16px;
}

.validation-hints {
  margin: 20px 0;
  padding: 16px;
  background: var(--ion-color-light);
  border-radius: 8px;
}

.hint-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--ion-color-danger);
  transition: color 0.3s ease;
}

.hint-item:last-child {
  margin-bottom: 0;
}

.hint-item.valid {
  color: var(--ion-color-success);
}

.hint-item ion-icon {
  font-size: 16px;
}

.register-button {
  margin-top: 20px;
  height: 48px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
}

.login-link p {
  color: var(--ion-color-medium);
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.login-link ion-button {
  --color: var(--ion-color-primary);
  font-weight: 600;
  margin: 0;
  height: auto;
  --padding-start: 4px;
  --padding-end: 4px;
}
</style>
